<template>
    <div>
        <div class="w-form-header">
            <!-- <span>创建规格图</span> -->

            <div>
                <el-button
                    v-if="!isEditing"
                    type="success"
                    :loading="saveLoading"
                    @click="enterDialog()"
                    >保存</el-button
                >
                <el-button
                    v-if="isEditing"
                    type="success"
                    @click="
                        () => {
                            isEditing = false;
                        }
                    "
                    >编辑</el-button
                >
                <el-button
                    v-if="route.query.ID"
                    :loading="partToSapLoading"
                    type="primary"
                    @click="partToSap"
                    >汇入SAP</el-button
                >
                <el-button
                    v-if="route.query.ID"
                    type="primary"
                    @click="updateToChanpin"
                    >同步规格配件信息</el-button
                >
            </div>
        </div>
        <div class="admin-content">
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">基础信息</div>
                    <el-form
                        :model="formData"
                        ref="elFormRef"
                        label-position="right"
                        :rules="rule"
                        label-width="150px"
                        :inline="true"
                        class="form-inline"
                    >
                        <el-form-item label="配件名称:" prop="accessoryName">
                            <!-- <el-input
                                :disabled="isEditing"
                                v-model="formData.accessoryName"
                                :clearable="true"
                                placeholder="请输入配件名称"
                            /> -->
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.accessoryName"
                                placeholder="请选择"
                                clearable
                                filterable
                            >
                                <el-option
                                    v-for="item in dictOptions.accessoryName"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="材质:" prop="materialProperty">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.materialProperty"
                                :clearable="true"
                                placeholder="请输入材质"
                            />
                        </el-form-item>

                        <el-form-item label="工序:" prop="workingProcedure">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.workingProcedure"
                                :clearable="true"
                                placeholder="请输入工序"
                            />
                        </el-form-item>

                        <el-form-item label="使用状态:" prop="usageStatus">
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.usageStatus"
                                placeholder="请选择"
                                clearable
                                filterable
                            >
                                <el-option
                                    v-for="item in dictOptions.inUserStatus"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="配件编号:" prop="accessoryNum">
                            <el-input
                                disabled
                                v-model="formData.accessoryNum"
                                :clearable="true"
                                placeholder="请输入配件编号"
                                @input="inputCheck('accessoryNum')"
                            />
                        </el-form-item>
                        <el-form-item label="颜色编号:" prop="colorNum">
                            <el-input
                                disabled
                                v-model="formData.colorNum"
                                @input="inputCheck('colorNum')"
                                :clearable="true"
                                placeholder="请输入"
                            />
                        </el-form-item>

                        <el-form-item label="物料尺码:" prop="materialSize">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.materialSize"
                                :clearable="true"
                                placeholder="请输入物料尺码"
                            />
                        </el-form-item>

                        <el-form-item label="单位:" prop="unit">
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.unit"
                                placeholder="请选择"
                                clearable
                                filterable
                            >
                                <el-option
                                    v-for="item in dictOptions.unit"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="物料说明:" prop="materialDesc">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.materialDesc"
                                :clearable="true"
                                placeholder="请输入物料说明"
                            />
                        </el-form-item>

                        <el-form-item label="物料群组:" prop="materialGroup">
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.materialGroup"
                                :clearable="true"
                                placeholder="请选择物料群组"
                                style="width: 100%"
                                filterable
                            >
                                <el-option
                                    :label="item.materialGroupNum"
                                    :value="item.materialGroupNum"
                                    v-for="item in materialGroupDocumentList"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            label="物料群组说明:"
                            prop="materialGroupDesc"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.materialGroupDesc"
                                :clearable="true"
                                placeholder="请输入物料群组说明"
                            />
                        </el-form-item>

                        <el-form-item label="" prop=""> </el-form-item>

                        <el-form-item
                            label="是否有模具:"
                            prop="isMoldAvailable"
                            v-if="!formData.colorNum"
                        >
                            <el-select
                                :disabled="isEditing || !!formData.colorNum"
                                v-model="formData.isMoldAvailable"
                                :clearable="true"
                                placeholder="请选择是否有模具"
                                style="width: 100%"
                            >
                                <el-option label="是" value="是" />
                                <el-option label="否" value="否" />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            label="是否辨别金胶共用:"
                            prop="isSpleenMetalShare"
                            v-if="!formData.colorNum"
                        >
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.isSpleenMetalShare"
                                :clearable="true"
                                placeholder="请选择"
                                style="width: 100%"
                                filterable
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in dictOptions.isSpleenMetalShare"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            label="已起模配架类型:"
                            prop="moldStartedType"
                            v-if="!formData.colorNum"
                        >
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.moldStartedType"
                                :clearable="true"
                                placeholder="请选择"
                                style="width: 100%"
                                filterable
                            >
                                <el-option label="金" :value="'1'" />
                                <el-option label="胶" :value="'2'" />
                                <el-option label="金胶共用" :value="'3'" />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            label="模具状态:"
                            prop="moldStatus"
                            v-if="!formData.colorNum"
                        >
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.moldStatus"
                                :clearable="true"
                                placeholder="请选择"
                                style="width: 100%"
                                filterable
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in dictOptions.moldStatus"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="是否外发:" prop="isOutSource">
                            <el-select
                                :disabled="isEditing"
                                v-model="formData.isOutSource"
                                :clearable="true"
                                placeholder="请选择是否外发"
                                style="width: 100%"
                                @change="isOutSourceChange"
                            >
                                <el-option label="是" value="是" />
                                <el-option label="否" value="否" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="外发需求:" prop="outSourceNeed">
                            <el-select
                                :disabled="
                                    isEditing || formData.isOutSource != '是'
                                "
                                v-model="formData.outSourceNeed"
                                :clearable="true"
                                placeholder="请选择"
                                style="width: 100%"
                                filterable
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in dictOptions.outSourceNeed"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="款式编号:" prop="styleNum">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.styleNum"
                                :clearable="true"
                                placeholder="请输入款式编号"
                            />
                        </el-form-item>

                        <!-- <el-form-item label="首办/大办:" prop="firstOrLarge">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.firstOrLarge"
                                :clearable="true"
                                placeholder="请输入首办/大办"
                            />
                        </el-form-item>
                   
                        <el-form-item
                            label="(首办)创建日期:"
                            prop="firstCreateAt"
                        >
                            <el-date-picker
                                :disabled="isEditing"
                                v-model="formData.firstCreateAt"
                                type="date"
                                style="width: 100%"
                                placeholder="选择日期"
                                :clearable="true"
                            />
                        </el-form-item>
                        
                        <el-form-item label="图纸编号:" prop="drawingNum">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.drawingNum"
                                :clearable="true"
                                placeholder="请输入图纸编号"
                            />
                        </el-form-item>
                       
                        <el-form-item
                            label="首办所属款号:"
                            prop="firstOrderNumBelongTo"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.firstOrderNumBelongTo"
                                :clearable="true"
                                placeholder="请输入首办所属款号"
                            />
                        </el-form-item>
                        <el-form-item
                            label="大办所属款号:"
                            prop="largeScaleNumBelongTo"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.largeScaleNumBelongTo"
                                :clearable="true"
                                placeholder="请输入大办所属款号"
                            />
                        </el-form-item>
                        <el-form-item
                            label="(首办)配件编号:"
                            prop="firstOrderAccessoryNum"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.firstOrderAccessoryNum"
                                :clearable="true"
                                placeholder="请输入(首办)配件编号"
                            />
                        </el-form-item>
                        <el-form-item
                            label="(首办)共用主档配件编号:"
                            prop="firstOrderShareDocumentAccessoryNum"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="
                                    formData.firstOrderShareDocumentAccessoryNum
                                "
                                :clearable="true"
                                placeholder="请输入(首办)共用主档配件编号"
                            />
                        </el-form-item>
                        <el-form-item
                            label="(首办)图纸编号:"
                            prop="firstOrderDrawingNum"
                        >
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.firstOrderDrawingNum"
                                :clearable="true"
                                placeholder="请输入(首办)图纸编号"
                            />
                        </el-form-item>
                        <el-form-item label="配件编号1:" prop="accessoryNum1">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.accessoryNum1"
                                :clearable="true"
                                placeholder="请输入配件编号1"
                            />
                        </el-form-item>
                        <el-form-item label="配件编号2:" prop="accessoryNum2">
                            <el-input
                                :disabled="isEditing"
                                v-model="formData.accessoryNum2"
                                :clearable="true"
                                placeholder="请输入配件编号2"
                            />
                        </el-form-item> -->
                    </el-form>
                </div>
                <div class="w-form-box">
                    <div class="list-header">操作记录</div>
                    <el-table
                        :data="logsCopy"
                        row-key="ida"
                        border="true"
                        style="width: 100%"
                    >
                        <el-table-column
                            type="index"
                            label="序号"
                            width="50"
                        ></el-table-column>
                        <el-table-column
                            prop="action"
                            label="操作"
                        ></el-table-column>
                        <el-table-column prop="differences" label="旧值">
                            <template #default="{ row }">
                                <div v-if="row.differences">
                                    <span v-for="item in row.differences">
                                        <span>{{ itemObj[item.field] }}:</span>
                                        <span>{{ item.old }}</span
                                        >；
                                    </span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="differences" label="新值">
                            <template #default="{ row }">
                                <div v-if="row.differences">
                                    <span v-for="item in row.differences">
                                        <span>{{ itemObj[item.field] }}:</span>
                                        <span>{{ item.new }}</span
                                        >；
                                    </span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="operator"
                            label="操作人"
                        ></el-table-column>
                        <el-table-column
                            prop="CreatedAt"
                            label="更新时间"
                        >
                        <template #default="{ row }">
                            {{formatDate(row.CreatedAt, 'yyyy:MM:dd hh:mm:ss')}}
                        </template>
                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: flex-end;">
                        <el-pagination
                            layout="total, sizes, prev, pager, next, jumper"
                            :current-page="page"
                            :page-size="pageSize"
                            :page-sizes="[20, 30, 50, 100]"
                            :total="total"
                            @current-change="handleCurrentChange"
                            @size-change="handleSizeChange"
                        />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {
    createAccessoryNumberDocument,
    deleteAccessoryNumberDocument,
    deleteAccessoryNumberDocumentByIds,
    updateAccessoryNumberDocument,
    findAccessoryNumberDocument,
    getAccessoryNumberDocumentList,
    partExportToSap,
    syncAccessoryNumberDocument,
} from "@/api/confAccessoryNumberDocument";
import { getMaterialGroupDocumentList } from "@/api/confMaterialGroupDocument";

// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { emitter } from "@/utils/bus.js";
import { useDict } from "@/utils/dictionary.js";
import { ref, reactive, onMounted, computed } from "vue";

import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

defineOptions({
    name: "AccessoryNumberDocument",
});

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
    // firstOrLarge: "",
    accessoryName: "",
    materialProperty: "",
    workingProcedure: "",
    accessoryNum: "",
    usageStatus: "",
    materialDesc: "",
    unit: "",
    materialGroupDesc: "",
    isMoldAvailable: "是",
    styleNum: "",
    isSpleenMetalShare: "",
    // firstCreateAt: new Date(),
    moldStartedType: "",
    materialGroup: "",
    materialSize: "",
    moldStatus: "",
    drawingNum: "",
    isOutSource: "",
    outSourceNeed: "",
    // firstOrderNumBelongTo: "",
    // largeScaleNumBelongTo: "",
    // firstOrderAccessoryNum: "",
    // firstOrderShareDocumentAccessoryNum: "",
    // firstOrderDrawingNum: "",
    // accessoryNum1: "",
    // accessoryNum2: "",
});
const dictOptions = ref({});
const saveLoading = ref(false);
let itemObj = ref({
    AccessoryName: "配件名称",
    MaterialProperty: "材质",
    WorkingProcedure: "工序",
    UsageStatus: "使用状态",
    AccessoryNum: "配件编号",
    ColorNum: "颜色编号",
    MaterialSize: "物料尺码",
    Unit: "单位",
    MaterialDesc: "物料说明",
    MaterialGroup: "物料群组",
    MaterialGroupDesc: "物料群组说明",
    IsMoldAvailable: "是否有模具",
    IsSpleenMetalShare: "是否辨别金胶共用",
    MoldStartedType: "已起模配架类型",
    MoldStatus: "模具状态",
    IsOutSource: "是否外发",
    OutSourceNeed: "外发需求",
    StyleNum: "款式编号",
});

// 验证规则
const rule = reactive({
    accessoryNum: [
        { required: true, message: "请输入配件编号", trigger: "blur" },
        {
            validator: function (rule, value, callback) {
                // 校验【英文-/.】组成
                const regex = /^[A-Z\.\-\/\d+]*$/;
                if (!regex.test(value)) {
                    callback(new Error("请输入合规内容"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
    accessoryName: [
        { required: true, message: "请输入配件名称", trigger: "blur" },
    ],
    materialGroup: [
        { required: true, message: "请选择物料群组", trigger: "change" },
    ],
    materialGroupDesc: [
        { required: true, message: "请输入物料群组说明", trigger: "blur" },
    ],
    materialDesc: [
        { required: true, message: "请输入物料说明", trigger: "blur" },
    ],
    unit: [{ required: true, message: "请选择单位", trigger: "change" }],
    outSourceNeed: [
        { required: false, message: "请选择外发需求", trigger: "change" },
    ],
});

const elFormRef = ref();
const elSearchFormRef = ref();

// =========== 表格控制部分 ===========
const page = ref(1);
const total = ref(0);
const pageSize = ref(20);

const logsCopy = computed(() => {
    let list = [];
    if (formData.value.logs) {
        list = formData.value.logs.slice(
            (page.value - 1) * pageSize.value,
            page.value * pageSize.value
        );
    }
    return list;
});

const isEditing = ref(false);

const dialogVisible = ref(false);
const differences = ref([]);

// 分页
const handleSizeChange = (val) => {
    pageSize.value = val;
};

// 修改页面容量
const handleCurrentChange = (val) => {
    page.value = val;
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 更新行
const updateAccessoryNumberDocumentFunc = async (row) => {
    const res = await findAccessoryNumberDocument({ ID: row.ID });
    type.value = "update";
    if (res.code === 0) {
        formData.value = res.data.reaccessoryNumberDocument;
        dialogFormVisible.value = true;
    }
};

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.ID) {
        const res = await findAccessoryNumberDocument({ ID: route.query.ID });
        type.value = "update";
        if (res.code === 0) {
            formData.value = res.data.reaccessoryNumberDocument;
            if (formData.value.logs) {
                total.value = formData.value.logs.length;
            }
        }
    } else {
        type.value = "create";
    }
};

init();

// 弹窗控制标记
const dialogFormVisible = ref(false);

// 查看详情控制标记
const detailShow = ref(false);

// 打开详情
const getDetails = async (row) => {
    // 打开弹窗
    const res = await findAccessoryNumberDocument({ ID: row.ID });
    if (res.code === 0) {
        formData.value = res.data.reaccessoryNumberDocument;
    }
};

// 物料群组
const materialGroupDocumentList = ref([]);
// 获取物料群组
const getMaterialGroupDocumentListFun = async () => {
    const table = await getMaterialGroupDocumentList({
        page: 1,
        pageSize: 999,
    });
    if (table.code === 0) {
        materialGroupDocumentList.value = table.data.list;
    }
};

const inputCheck = (key) => {
    // 去除空格
    formData.value[key] = formData.value[key].replace(/\s+/g, "");
    // 将小写转为大写
    formData.value[key] = formData.value[key].toUpperCase();
};
// 弹窗确定
const enterDialog = async () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let submitForm = Object.assign({}, formData.value);
        if (submitForm.logs) delete submitForm.logs;
        let str = submitForm.accessoryNum + submitForm.colorNum;
        if (str.length > 18) {
            ElMessage({
                type: "error",
                message: "主档编号+颜色编号不能超过18位",
            });
            return;
        }
        let res;
        saveLoading.value = true;
        switch (type.value) {
            case "create":
                res = await createAccessoryNumberDocument(submitForm);
                saveLoading.value = false;
                ElMessage({
                    type: "success",
                    message: "创建成功",
                });
                emitter.emit("closeThisPage", {
                    path: "/layout/accessoryNumberDocument",
                });
                break;
            case "update":
                res = await updateAccessoryNumberDocument(submitForm);
                saveLoading.value = false;
                ElMessage({
                    type: "success",
                    message: "修改成功",
                });
                init();
                break;
            default:
                res = await createAccessoryNumberDocument(submitForm);
                break;
        }
    });
};

// 汇入sap
let partToSapLoading = ref(false);
const partToSap = () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let submitForm = Object.assign({}, formData.value);
        if (submitForm.logs) delete submitForm.logs;
        let str = submitForm.accessoryNum + submitForm.colorNum;
        if (str.length > 18) {
            ElMessage({
                type: "error",
                message: "主档编号+颜色编号不能超过18位",
            });
            return;
        }
        partToSapLoading.value = true;
        switch (type.value) {
            case "update":
                updateAccessoryNumberDocument(submitForm).then((res) => {
                    if (res.code == 0) {
                        partExportToSap({ id: route.query.ID })
                            .then((res) => {
                                init();
                                partToSapLoading.value = false;
                                if (res.code == 0) {
                                    ElMessage({
                                        type: "success",
                                        message: "汇入成功",
                                    });
                                }
                            })
                            .catch((err) => {
                                partToSapLoading.value = false;
                                init();
                            });
                    }
                });
                break;
        }
    });
};
const updateToChanpin = () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let submitForm = Object.assign({}, formData.value);
        if (submitForm.logs) delete submitForm.logs;
        let str = submitForm.accessoryNum + submitForm.colorNum;
        if (str.length > 18) {
            ElMessage({
                type: "error",
                message: "主档编号+颜色编号不能超过18位",
            });
            return;
        }
        syncAccessoryNumberDocument(submitForm).then((res) => {
            init();
            if (res.code == 0) {
                ElMessage({
                    type: "success",
                    message: "更新成功",
                });
            }
        });
    });
};

// 新加需求配件编号主档：是否外发、外发需求
// 是否外发默认空、外发需要默认禁用
// 是否外发：是，外发需求必填
// 是否外发：否，外发需求禁用

function isOutSourceChange(params) {
    console.log(params);
    if (params == "是") {
        rule.outSourceNeed[0].required = true;
    } else {
        rule.outSourceNeed[0].required = false;
        formData.value.outSourceNeed = "";
    }
}

onMounted(async () => {
    getMaterialGroupDocumentListFun();
    dictOptions.value = await useDict(
        "unit",
        "moldStatus",
        "inUserStatus",
        "isSpleenMetalShare",
        "outSourceNeed",
        "accessoryName"
    );
    if (route.query.ID) {
        isEditing.value = true;
    } else {
        isEditing.value = false;
    }
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
:deep(.el-select__wrapper) {
    padding: 0;
}
</style>
